<template>
  <el-dialog title="时长编辑" :visible.sync="visible" width="30%" :before-close="handleClose" :close-on-click-modal="false" :inline="true">
    <el-form ref="duration" label-position="left" label-width="80px" :model="attach" size="small">
      <el-form-item prop="duration" :rules="rules">
        <template v-slot:label>
          <span>时长</span>
          <el-popover trigger="hover" transition="el-zoom-in-bottom" placement="top" popper-class="popper">
            <div>格式: 00:00:00</div>
            <template v-slot:reference><i class="edu-icon-info" /></template>
          </el-popover>
        </template>
        <el-input v-model="attach.duration" type="text" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    item: {
      type: Object,
      require: true,
      default: _ => {
        return {};
      }
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      attach: {
        duration: '00:00:00'
      },
      rules: [
        { required: true, message: '请填写时长', trigger: ['blur', 'change'] },
        {
          pattern: /^\d{2,}:\d{2}:\d{2}$/,
          message: '请输入正确的时长格式',
          trigger: ['blur', 'change']
        }
      ]
    };
  },
  created() {
    const duration = this.item.duration_format;
    this.$set(this.attach, 'duration', duration);
  },
  methods: {
    handleClose: function() {
      this.$emit('update:visible', false);
    },
    onSubmit: function() {
      this.$refs['duration'].validate((valid, object) => {
        if (valid) {
          const data = {
            duration: this.attach.duration
          };
          this.$http.put(
            '/admin/material/update/' + this.item.id + '/duration',
            data,
            _ => {
              this.$message.success('操作成功');
              this.$emit('update:duration', {
                id: this.item.id,
                ...data
              });
              this.$emit('update:visible', false);
            },
            _ => {
              this.$message.error('操作失败');
            },
            false
          );
        }
      });
    }
  }
};
</script>
